import { Request, Response } from 'express'
import { PrismaClient } from '@prisma/client'
import { validateWorkflow } from '../utils/workflow'
import { executeWorkflowAsync } from '../services/workflow'
import { logger } from '../services/logger'

const prisma = new PrismaClient()

// 获取工作流列表
export const getWorkflows = async (req: Request, res: Response) => {
    try {
        const { type = 'all', search = '', page = 1, limit = 10 } = req.query
        const userId = req.user?.id

        if (!userId) {
            return res.status(401).json({ error: '未授权' })
        }

        const where: any = {
            OR: [
                { name: { contains: search as string } },
                { title: { contains: search as string } },
                { description: { contains: search as string } }
            ]
        }

        if (type !== 'all') {
            where.type = type
        }

        // 计算分页
        const skip = (Number(page) - 1) * Number(limit)
        const take = Number(limit)

        // 查询数据
        const [workflows, total] = await Promise.all([
            prisma.workflow.findMany({
                where,
                orderBy: [
                    { sort: 'asc' },
                    { updatedAt: 'desc' }
                ],
                skip,
                take
            }),
            prisma.workflow.count({ where })
        ])

        res.json({
            items: workflows,
            total,
            page: Number(page),
            limit: Number(limit),
            pages: Math.ceil(total / Number(limit))
        })
    } catch (error) {
        logger.error('Failed to get workflows:', error)
        res.status(500).json({ error: '获取工作流列表失败' })
    }
}

// 获取工作流详情
export const getWorkflow = async (req: Request, res: Response) => {
    try {
        const { id } = req.params
        const userId = req.user?.id

        if (!userId) {
            return res.status(401).json({ error: '未授权' })
        }

        const workflow = await prisma.workflow.findUnique({
            where: { id }
        })

        if (!workflow) {
            return res.status(404).json({ error: '工作流不存在' })
        }

        res.json(workflow)
    } catch (error) {
        logger.error('Failed to get workflow:', error)
        res.status(500).json({ error: '获取工作流失败' })
    }
}

// 获取工作流模板
export const getWorkflowTemplate = async (req: Request, res: Response) => {
    try {
        const { id } = req.params
        const workflow = await prisma.workflow.findUnique({
            where: { id },
            select: { template: true }
        })

        if (!workflow) {
            return res.status(404).json({ error: '工作流不存在' })
        }

        res.json(JSON.parse(workflow.template))
    } catch (error) {
        logger.error('Failed to get workflow template:', error)
        res.status(500).json({ error: '获取工作流模板失败' })
    }
}

// 创建工作流
export const createWorkflow = async (req: Request, res: Response) => {
    try {
        const userId = req.user?.id
        const data = { ...req.body, userId }

        // 验证工作流配置
        if (!validateWorkflow(JSON.parse(data.workflow))) {
            return res.status(400).json({ error: '无效的工作流配置' })
        }

        const workflow = await prisma.workflow.create({ data })
        res.json(workflow)
    } catch (error) {
        logger.error('Failed to create workflow:', error)
        res.status(500).json({ error: '创建工作流失败' })
    }
}

// 更新工作流
export const updateWorkflow = async (req: Request, res: Response) => {
    try {
        const { id } = req.params
        const userId = req.user?.id
        const data = req.body

        // 验证工作流配置
        if (data.workflow && !validateWorkflow(JSON.parse(data.workflow))) {
            return res.status(400).json({ error: '无效的工作流配置' })
        }

        const workflow = await prisma.workflow.update({
            where: { id },
            data
        })

        res.json(workflow)
    } catch (error) {
        logger.error('Failed to update workflow:', error)
        res.status(500).json({ error: '更新工作流失败' })
    }
}

// 删除工作流
export const deleteWorkflow = async (req: Request, res: Response) => {
    try {
        const { id } = req.params
        const userId = req.user?.id

        await prisma.workflow.delete({ where: { id } })
        res.status(204).end()
    } catch (error) {
        logger.error('Failed to delete workflow:', error)
        res.status(500).json({ error: '删除工作流失败' })
    }
}

// 执行工作流
export const executeWorkflow = async (req: Request, res: Response) => {
    try {
        const { id } = req.params
        const userId = req.user!.id
        const params = req.body

        // 创建执行记录
        const execution = await prisma.execution.create({
            data: {
                status: 'pending',
                params: JSON.stringify(params),
                workflowId: id,
                userId
            },
            include: {
                workflow: true,
                user: {
                    select: {
                        id: true,
                        username: true,
                        email: true
                    }
                }
            }
        })

        // 异步执行工作流
        executeWorkflowAsync(execution)
            .catch((error: Error) => {
                logger.error('Workflow execution failed:', error)
            })

        res.json(execution)
    } catch (error) {
        logger.error('Create execution failed:', error)
        res.status(500).json({ error: '创建执行记录失败' })
    }
}

// 获取执行历史
export const getExecutionHistory = async (req: Request, res: Response) => {
    try {
        const { workflowId } = req.params
        const { page = 1, limit = 10 } = req.query

        const executions = await prisma.execution.findMany({
            where: {
                workflowId
            },
            include: {
                workflow: true,
                user: {
                    select: {
                        id: true,
                        username: true,
                        email: true
                    }
                }
            },
            orderBy: {
                createdAt: 'desc'
            },
            skip: (Number(page) - 1) * Number(limit),
            take: Number(limit)
        })

        res.json(executions)
    } catch (error) {
        logger.error('Get execution history failed:', error)
        res.status(500).json({ error: '获取执行历史失败' })
    }
}

// 获取执行状态
export const getExecutionStatus = async (req: Request, res: Response) => {
    try {
        const { executionId } = req.params
        const userId = req.user?.id

        const execution = await prisma.execution.findFirst({
            where: {
                id: executionId,
                userId
            }
        })

        if (!execution) {
            return res.status(404).json({ error: '执行记录不存在' })
        }

        res.json(execution)
    } catch (error) {
        logger.error('Failed to get execution status:', error)
        res.status(500).json({ error: '获取执行状态失败' })
    }
}